package com.example.demo.exception;

import com.example.demo.utils.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.logging.Logger;

/**
 * 统一异常处理类
 *
 * @author chen huilong
 * @since 2022-10-04
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    // 指定出现什么异常执行这个方法
    @ExceptionHandler(Exception.class)
    @ResponseBody //为了返回数据
    public Response error(Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return Response.error().message("全局异常处理");
    }

    //特定异常
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public Response error(ArithmeticException e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return Response.error().message("ArithmeticException异常");
    }

    //自定义异常
    @ExceptionHandler(CmsException.class)
    @ResponseBody //为了返回数据
    public Response error(CmsException e) {
        // 写日志文件
        log.error(e.getMessage());
        e.printStackTrace();
        return Response.error().code(e.getCode()).message(e.getMsg());
    }
}
